package com.opm.security.core.util;

import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

public class UserUtil {

   public static String getCurrentUsername(){
      UserDetails userDetails = getAuthenticated();
      return userDetails.getUsername();
   }

   public static String getGuestUsername(){
      String guestName = "AnonymousUser";
      return guestName;
   }

   public static boolean hasAuthenticated() {
      boolean result = (getAuthenticated() != null)?true:false;
      return result;
   }

   public static UserDetails getAuthenticated() {
      SecurityContext securityContext = SecurityContextHolder.getContext();
      if (securityContext != null && securityContext.getAuthentication() != null) {
         Object principal = securityContext.getAuthentication().getPrincipal();
         if (principal instanceof UserDetails){
            return (UserDetails) principal;
         }
      }
      return null;
   }
}
